#include <my_header.h>

/* Usage: ./2_client_select */
int main(void){                                  
    // 服务器ip和端口
    char *port = "8080";
    char *ip = "192.168.229.128";

    // socket端点文件描述符
    int socket_fd = socket(AF_INET, SOCK_STREAM,0);
    ERROR_CHECK(socket_fd, -1, "socket");

    // 构建 struct sockaddr 类型
    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;  // ipv4
    sockaddr.sin_port = htons(atoi(port));  // 端口
    sockaddr.sin_addr.s_addr = inet_addr(ip);   // ip地址
                                
    // 连接
    int res_connectd = connect(socket_fd, (struct sockaddr *)&sockaddr, sizeof(sockaddr));
    ERROR_CHECK(res_connectd, -1, "connect");
    //创建监听集合
    fd_set set;
    while(1)
    {
        // 设置监听集合
        FD_ZERO(&set);
        FD_SET(STDIN_FILENO, &set);
        FD_SET(socket_fd, &set);

        // 使用select监听set集合是否可读
        int res_select = select(socket_fd +1, &set, NULL, NULL, NULL);
        ERROR_CHECK(res_select, 0, "timed");
        ERROR_CHECK(res_select, -1, "select");

        // 就绪
        if(FD_ISSET(STDIN_FILENO, &set))
        {
            // 读取标准输入,给对方回信息
            char buf[60] = { 0 };
            read(STDIN_FILENO, buf, sizeof(buf));
            send(socket_fd, buf, sizeof(buf), 0);
        }
        if(FD_ISSET(socket_fd, &set))
        {
            char buf[60] = {0};
            // 读取网络数据->打印
            ssize_t ret = recv(socket_fd, buf, sizeof(buf), 0);
                if(ret == 0)
                {
                    printf("server close \n");
                    break;
                }
            printf("client message:%s \n", buf);
        }
    }
    // 关闭端点文件描述符
    close(socket_fd);
    return 0;
}


